<?php
/**
 * Function:
 * Description:
 * Abo 2019/1/20 20:00
 * Email: abo2013@foxmail.com
 */

namespace Abo\Fasterapi\V0\Logics;

class RedisCacheLogic
{
    public $redis;
    public function __construct()
    {
        $this->redis = $this->redisInstance();
    }

    /**  */
    public function refreshCache( $redisKey, $cacheKey, $cacheValue )
    {

        $codeList = $this->redis->get( $redisKey );
        if( !$codeList ) {
            $codeList = [];
        }else{
            $codeList = json_decode( $codeList, true );
        }

        $codeList[$cacheKey] = $cacheValue;
        return $this->redis->set( $redisKey, $codeList );
    }

    /** 删除缓存 支持模糊删除 */
    public function delCache( string $cacheKey = '' )
    {
        if ( !$cacheKey ){ return false; }

        $keys = $this->redis->keys( $cacheKey.'*' );
        if ( !$keys ) { return false; }

        foreach ( $keys as $v2Key ) {
            $tem = $this->redis->del( $v2Key );
        }

        return true;
    }

    public function redisInstance() {
        if ( !$this->redis ) { return $this->redis; }

        return $this->redis = self::redisFactory();
    }

    public static function redisFactory()
    {
        // $redis = app('rediscache');

        $redis = new \Redis;
        $redis->pconnect( env('REDIS_CACHE_HOST', '127.0.0.1'), env('REDIS_CACHE_PORT', 6379) );
        $redis->select(0);
        return $redis;
    }
}